package cn.tedu.sp11.filter;

import cn.tedu.sp01.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //指定过滤器的类型，"pre"-前置过滤器,"routes","post","error"
    @Override
    public String filterType() {
        //return "pre"
        return FilterConstants.PRE_TYPE;
    }

    //指定过滤器添加的位置序号
    @Override
    public int filterOrder() {
        return 6;
    }

    // 判断针对当前这次请求，是否要执行过滤代码
    // 如果请求 item-service，执行全选判断
    // 如果请求 user 或 order，直接跳过过滤代码
    @Override
    public boolean shouldFilter() {
        //获得正在调用的服务id
        RequestContext ctx=RequestContext.getCurrentContext();
        String serviceId=(String)ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/y4tg32t243?token=u45t34

        //得到request对象
        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        //接收 token 参数
        String token=request.getParameter("token");
        //如果 token 参数不存在，阻止继续调用，直接返回提示
        if(StringUtils.isBlank(token)){
            //阻止继续访问
            ctx.setSendZuulResponse(false);

            //返回登录提示
            //JsonResult -{code:400,msg:"not long in",data:null}
            String json=JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("not long,没有登录")
                    .toString();

            ctx.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }

        return null;//返回任何数据都无效
    }
}
